package com.quwan.security;

import com.alibaba.fastjson.JSONObject;
import com.quwan.common.result.ApiResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

/**
 * @author quan
 * @date 2021-06-08 10:03
 */

@Component
public class JwtEntryPoint implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        //  response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未授权");
        ApiResult<String> res = ApiResult.error(HttpServletResponse.SC_UNAUTHORIZED, "请登录");
        response.setContentType("text/JavaScript;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        PrintWriter writer = response.getWriter();
        writer.print((JSONObject.toJSONString(res)));
        writer.flush();
    }
}
